package com.orhon.smartcampus.modules.student.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.student.dao.TrafficDao;
import com.orhon.smartcampus.modules.student.entity.Traffic;
import com.orhon.smartcampus.modules.student.gqlInputModel.GQLTrafficsInput;
import com.orhon.smartcampus.modules.student.inputMapper.TrafficsInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddTrafficMutation implements DataFetcher {
	@Autowired
	TrafficDao trafficDao;

    @Autowired
    TokenService tokenService;


    /**
     * 新增/修改届信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);
      
        GQLTrafficsInput input = TrafficsInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));
        Traffic traffic = null;
        if (input.getId() != null){
        	traffic = trafficDao.get(Traffic.class , input.getId());
        	traffic.setUpdatedAt(new Date());
        }
        else{
        	traffic = new Traffic();
        	traffic.setCreatedAt(new Date());
        }
        if(input.getStudentId() != null){
        	traffic.setStudentId(input.getStudentId());
        }
        if(input.getUserId() != null){
        	traffic.setUserId(input.getUserId());
        }
        if(input.getDistance() != null){
        	traffic.setDistance(input.getDistance());
        }
        if(input.getTrafficReleaseId() != null){
        	traffic.setTrafficReleaseId(input.getTrafficReleaseId());
        }
        if(input.getIsSchoolB() != null){
        	traffic.setIsSchoolBus(input.getIsSchoolB());
        }

        try{
        	trafficDao.saveOrUpdate(traffic);
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }

        return traffic;
    }
}

